#include "buildLight.h"

#include <lights/point.h>
#include <core/transform.h>

#include <FnAttribute/FnAttribute.h>
#include <RenderOutputUtils/RenderOutputUtils.h>

#include <iostream>


int getLights( FnKat::Render::RenderSettings &renderSettings,
               FnKat::FnScenegraphIterator rootIt,
               FnKat::GroupAttribute lightListAttr,
               vector<Light*> &lights)
{
    int lightsCount = 0;
    int numChildren = lightListAttr.getNumberOfChildren();

    for(int i = 0; i < numChildren; ++i)
    {
        FnKat::GroupAttribute lightAttr = lightListAttr.getChildByIndex(i);

        if(!lightAttr.isValid())
        {
            cerr << "LightAttr not found!" << endl;
            continue;
        }

        FnKat::IntAttribute enableAttr = lightAttr.getChildByName("enable");
        if (!enableAttr.isValid() || !enableAttr.getValue())
        {
            cerr << "LightAttr not enabled!" << endl;
            continue;
        }

        FnKat::StringAttribute lightPathAttr = lightAttr.getChildByName("path");
        if(!lightPathAttr.isValid())
        {
            cerr << "LightAttr.path not found!" << endl;
            continue;
        }

        string lightPath = lightPathAttr.getValue();
        FnKat::FnScenegraphIterator lightIt = rootIt.getByPath(lightPath);
        if(!lightIt.isValid())
        {
            cerr << "LightIt not found!  " << lightPath << endl;
            continue;
        }

        FnKat::StringAttribute typeAttr = lightIt.getAttribute("type");
        if(!typeAttr.isValid() || typeAttr.getValue() != "light")
        {
            cerr << "LightIt is not a light!  " << lightPath << endl;
            continue;
        }

        Light *light = getLight(renderSettings, lightIt);
        if(light != NULL)
        {
            lights.push_back(light);
            lightsCount++;
        }
    }

    return lightsCount;
}

Light * getLight(FnKat::Render::RenderSettings &renderSettings, FnKat::FnScenegraphIterator lightIt)
{
    //TODO
    ParamSet p;
    Point from(0.0f, 0.0f, 0.0f);

    float rgb[3] = {3000, 3000, 3000};
    p.AddRGBSpectrum("I", rgb, 3);

    FnKat::GroupAttribute xformAttr = FnKat::RenderOutputUtils::getCollapsedXFormAttr(lightIt);

    FnKat::GroupAttribute lightXformAttr = xformAttr.getChildByIndex(0);
    if(lightXformAttr.isValid())
    {
        FnKat::GroupAttribute interactiveAttr = lightXformAttr.getChildByIndex(0);
        if(interactiveAttr.isValid())
        {
            FnKat::DoubleAttribute translateAttr = interactiveAttr.getChildByName("translate");
            if( translateAttr.isValid() )
            {
                FnKat::DoubleConstVector values = translateAttr.getNearestSample(0);
                from = Point(values[0], values[1], values[2]);
            }
        }
    }

    p.AddPoint("from", &from, 1);

    Transform light2world;
    return CreatePointLight(light2world, p);
}
